import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Shuffle, Clock, Trophy, Star, CheckCircle, XCircle, Zap, Brain, Target, AlertCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface CognitiveFlexibilityTestProps {
  onComplete: (result: TestResult) => void;
}

interface Trial {
  id: number;
  shape: 'circle' | 'square' | 'triangle' | 'diamond' | 'hexagon';
  color: 'red' | 'blue' | 'green' | 'yellow' | 'purple' | 'orange';
  size: 'small' | 'medium' | 'large';
  rule: 'shape' | 'color' | 'size' | 'mixed';
  correct: boolean;
  ruleSpecific?: string; // 具体的规则描述
}

interface FeedbackState {
  show: boolean;
  correct: boolean;
  reactionTime: number;
}

export function CognitiveFlexibilityTest({ onComplete }: CognitiveFlexibilityTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentTrial, setCurrentTrial] = useState(0);
  const [currentRule, setCurrentRule] = useState<'shape' | 'color' | 'size' | 'mixed'>('shape');
  const [trials, setTrials] = useState<Trial[]>([]);
  const [responses, setResponses] = useState<boolean[]>([]);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(420); // 7分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [trialStartTime, setTrialStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [switchTrials, setSwitchTrials] = useState<number[]>([]);
  const [feedback, setFeedback] = useState<FeedbackState>({ show: false, correct: false, reactionTime: 0 });
  const [streakCount, setStreakCount] = useState(0);
  const [maxStreak, setMaxStreak] = useState(0);
  const [switchPerformance, setSwitchPerformance] = useState<{ correct: number; total: number }>({ correct: 0, total: 0 });
  const [awaitingResponse, setAwaitingResponse] = useState(true);

  const MAX_TRIALS = 80; // 增加试次数量
  const feedbackTimeoutRef = useRef<NodeJS.Timeout>();

  // 规则定义
  const ruleDefinitions = {
    shape: {
      description: '形状规则',
      criteria: '圆形、三角形、六边形为正确',
      correct: ['circle', 'triangle', 'hexagon'],
      color: 'blue'
    },
    color: {
      description: '颜色规则', 
      criteria: '红色、蓝色、紫色为正确',
      correct: ['red', 'blue', 'purple'],
      color: 'purple'
    },
    size: {
      description: '大小规则',
      criteria: '中等、大型尺寸为正确',
      correct: ['medium', 'large'],
      color: 'green'
    },
    mixed: {
      description: '组合规则',
      criteria: '大型红色或小型蓝色为正确',
      correct: [], // 特殊处理
      color: 'orange'
    }
  };

  const generateTrials = (): Trial[] => {
    const shapes: Array<'circle' | 'square' | 'triangle' | 'diamond' | 'hexagon'> = 
      ['circle', 'square', 'triangle', 'diamond', 'hexagon'];
    const colors: Array<'red' | 'blue' | 'green' | 'yellow' | 'purple' | 'orange'> = 
      ['red', 'blue', 'green', 'yellow', 'purple', 'orange'];
    const sizes: Array<'small' | 'medium' | 'large'> = ['small', 'medium', 'large'];
    const rules: Array<'shape' | 'color' | 'size' | 'mixed'> = ['shape', 'color', 'size', 'mixed'];
    
    const newTrials: Trial[] = [];
    const switchPositions: number[] = [];
    let currentRule: 'shape' | 'color' | 'size' | 'mixed' = 'shape';
    
    // 更智能的切换策略 - 确保每种规则都有足够的试次
    let nextSwitch = 12; // 第一次切换
    while (nextSwitch < MAX_TRIALS) {
      switchPositions.push(nextSwitch);
      nextSwitch += Math.floor(Math.random() * 8) + 8; // 8-15个试次后切换
    }
    
    setSwitchTrials(switchPositions);

    for (let i = 0; i < MAX_TRIALS; i++) {
      if (switchPositions.includes(i)) {
        // 随机切换到不同的规则
        const availableRules = rules.filter(r => r !== currentRule);
        currentRule = availableRules[Math.floor(Math.random() * availableRules.length)];
      }
      
      const shape = shapes[Math.floor(Math.random() * shapes.length)];
      const color = colors[Math.floor(Math.random() * colors.length)];
      const size = sizes[Math.floor(Math.random() * sizes.length)];
      
      // 根据当前规则确定正确性
      let correct: boolean;
      let ruleSpecific: string = '';
      
      switch (currentRule) {
        case 'shape':
          correct = ruleDefinitions.shape.correct.includes(shape);
          ruleSpecific = `形状规则：${ruleDefinitions.shape.criteria}`;
          break;
        case 'color':
          correct = ruleDefinitions.color.correct.includes(color);
          ruleSpecific = `颜色规则：${ruleDefinitions.color.criteria}`;
          break;
        case 'size':
          correct = ruleDefinitions.size.correct.includes(size);
          ruleSpecific = `大小规则：${ruleDefinitions.size.criteria}`;
          break;
        case 'mixed':
          correct = (size === 'large' && color === 'red') || (size === 'small' && color === 'blue');
          ruleSpecific = `组合规则：${ruleDefinitions.mixed.criteria}`;
          break;
        default:
          correct = false;
      }
      
      newTrials.push({
        id: i + 1,
        shape,
        color,
        size,
        rule: currentRule,
        correct,
        ruleSpecific
      });
    }
    
    return newTrials;
  };

  useEffect(() => {
    if (stage === 'test') {
      const newTrials = generateTrials();
      setTrials(newTrials);
      setCurrentRule(newTrials[0].rule);
      setTrialStartTime(Date.now());
    }
  }, [stage]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
  };

  const handleResponse = (userResponse: boolean) => {
    if (!awaitingResponse) return;
    
    const reactionTime = Date.now() - trialStartTime;
    const trial = trials[currentTrial];
    const correct = userResponse === trial.correct;
    const isSwitch = switchTrials.includes(currentTrial);
    
    setAwaitingResponse(false);
    setResponses(prev => [...prev, userResponse]);
    setReactionTimes(prev => [...prev, reactionTime]);
    
    // 显示即时反馈
    setFeedback({ show: true, correct, reactionTime });
    
    if (correct) {
      setScore(prev => prev + 1);
      setStreakCount(prev => {
        const newStreak = prev + 1;
        setMaxStreak(current => Math.max(current, newStreak));
        return newStreak;
      });
    } else {
      setStreakCount(0);
    }

    // 跟踪切换试次的表现
    if (isSwitch) {
      setSwitchPerformance(prev => ({
        correct: prev.correct + (correct ? 1 : 0),
        total: prev.total + 1
      }));
    }

    // 1秒后进入下一试次
    feedbackTimeoutRef.current = setTimeout(() => {
      setFeedback({ show: false, correct: false, reactionTime: 0 });
      setAwaitingResponse(true);
      
      if (currentTrial < trials.length - 1) {
        const nextTrial = currentTrial + 1;
        setCurrentTrial(nextTrial);
        setCurrentRule(trials[nextTrial].rule);
        setTrialStartTime(Date.now());
      } else {
        setStage('results');
      }
    }, 1000);
  };

  const handleComplete = () => {
    // Ensure we have valid data
    if (!trials.length || !responses.length || !reactionTimes.length) {
      console.error('Invalid test data for completion');
      return;
    }

    // Synchronize arrays
    const minLength = Math.min(responses.length, trials.length, reactionTimes.length);
    const validResponses = responses.slice(0, minLength);
    const validTrials = trials.slice(0, minLength);
    const validReactionTimes = reactionTimes.slice(0, minLength);
    
    const correctResponses = validResponses.map((response, index) => 
      response === validTrials[index]?.correct
    ).filter(result => result !== undefined);
    
    const accuracy = correctResponses.length > 0 ? 
      Math.round((correctResponses.filter(Boolean).length / correctResponses.length) * 100) : 0;
    const averageRT = validReactionTimes.length > 0 ? 
      Math.round(validReactionTimes.reduce((sum, rt) => sum + rt, 0) / validReactionTimes.length) : 0;
    
    // 分别计算不同规则的准确率
    const rulePerformance: Record<string, { correct: number; total: number }> = {};
    validTrials.forEach((trial, index) => {
      if (!trial || !trial.rule) return; // Safety check
      
      if (!rulePerformance[trial.rule]) {
        rulePerformance[trial.rule] = { correct: 0, total: 0 };
      }
      rulePerformance[trial.rule].total++;
      if (correctResponses[index]) {
        rulePerformance[trial.rule].correct++;
      }
    });
    
    // 计算切换成本
    const switchCosts: number[] = [];
    const nonSwitchRTs: number[] = [];
    const switchRTs: number[] = [];
    
    validReactionTimes.forEach((rt, index) => {
      if (!rt || isNaN(rt)) return; // Safety check
      
      if (switchTrials.includes(index)) {
        switchRTs.push(rt);
        // 计算与前一个非切换试次的差异
        const prevRT = validReactionTimes[Math.max(0, index - 1)];
        if (prevRT && !isNaN(prevRT)) {
          switchCosts.push(rt - prevRT);
        }
      } else {
        nonSwitchRTs.push(rt);
      }
    });
    
    const averageSwitchCost = switchCosts.length > 0 ? 
      Math.round(switchCosts.reduce((sum, cost) => sum + cost, 0) / switchCosts.length) : 0;
    
    const switchAccuracy = switchPerformance.total > 0 ? 
      Math.round((switchPerformance.correct / switchPerformance.total) * 100) : 0;
    
    // 复杂评分算法
    let finalScore = 0;
    
    // 基础准确率 (40%)
    finalScore += accuracy * 0.4;
    
    // 切换适应能力 (30%)
    const switchAdaptation = Math.max(0, switchAccuracy - 20); // 切换准确率需要达到20%基准
    finalScore += switchAdaptation * 0.3;
    
    // 反应速度 (15%)
    const speedScore = Math.max(0, Math.min(100, (3000 - averageRT) / 20)); // 3秒内反应越快分数越高
    finalScore += speedScore * 0.15;
    
    // 一致性 (10%)
    const rtVariance = validReactionTimes.length > 1 ? 
      validReactionTimes.reduce((sum, rt) => sum + Math.pow(rt - averageRT, 2), 0) / validReactionTimes.length : 0;
    const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 20);
    finalScore += consistencyScore * 0.1;
    
    // 切换成本惩罚 (5%)
    const switchCostPenalty = Math.min(20, averageSwitchCost / 50);
    finalScore -= switchCostPenalty * 0.05;
    
    finalScore = Math.round(Math.max(0, Math.min(100, finalScore)));

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'cognitive-flexibility',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTrials: validTrials.length,
        correctResponses: correctResponses.filter(Boolean).length,
        accuracy,
        averageReactionTime: averageRT,
        switchTrials: switchTrials.length,
        switchAccuracy,
        averageSwitchCost,
        maxStreak,
        flexibilityIndex: Math.round(100 - Math.max(0, averageSwitchCost / 20)),
        rulePerformance: Object.entries(rulePerformance).reduce((acc, [rule, perf]) => {
          acc[rule] = perf.total > 0 ? Math.round((perf.correct / perf.total) * 100) : 0;
          return acc;
        }, {} as Record<string, number>),
        consistencyScore: Math.round(consistencyScore),
        speedScore: Math.round(speedScore)
      }
    };

    onComplete(result);
  };

  const renderShape = (shape: string, color: string, size: string) => {
    const sizeClasses = {
      small: 'w-16 h-16',
      medium: 'w-24 h-24', 
      large: 'w-32 h-32'
    };
    
    const baseClasses = `${sizeClasses[size as keyof typeof sizeClasses]} mx-auto shadow-lg transition-all duration-300`;
    
    const colorClasses = {
      red: 'bg-red-500',
      blue: 'bg-blue-500',
      green: 'bg-green-500',
      yellow: 'bg-yellow-500',
      purple: 'bg-purple-500',
      orange: 'bg-orange-500'
    };

    const colorClass = colorClasses[color as keyof typeof colorClasses];

    switch (shape) {
      case 'circle':
        return <div className={`${baseClasses} ${colorClass} rounded-full`} />;
      case 'square':
        return <div className={`${baseClasses} ${colorClass} rounded-lg`} />;
      case 'triangle':
        return (
          <div className={`${sizeClasses[size as keyof typeof sizeClasses]} mx-auto relative`}>
            <div 
              className={`absolute inset-0 ${colorClass} shadow-lg`}
              style={{
                clipPath: 'polygon(50% 0%, 0% 100%, 100% 100%)'
              }}
            />
          </div>
        );
      case 'diamond':
        return (
          <div className={`${sizeClasses[size as keyof typeof sizeClasses]} mx-auto relative`}>
            <div 
              className={`absolute inset-0 ${colorClass} shadow-lg transform rotate-45`}
              style={{ borderRadius: '8px' }}
            />
          </div>
        );
      case 'hexagon':
        return (
          <div className={`${sizeClasses[size as keyof typeof sizeClasses]} mx-auto relative`}>
            <div 
              className={`absolute inset-0 ${colorClass} shadow-lg`}
              style={{
                clipPath: 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)'
              }}
            />
          </div>
        );
      default:
        return null;
    }
  };

  // 清理定时器
  useEffect(() => {
    return () => {
      if (feedbackTimeoutRef.current) {
        clearTimeout(feedbackTimeoutRef.current);
      }
    };
  }, []);

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-3xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Shuffle className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">认知灵活性测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的思维转换和多规则适应能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl p-6 border border-teal-100">
              <h3 className="font-semibold text-teal-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>您将看到不同形状、颜色和大小的图形</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>按照当前规则判断图形是否"正确"，每次回答后会有即时反馈</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>规则会随机切换，请快速适应新规则</p>
                </div>
              </div>
            </div>

            {/* 规则说明 */}
            <div className="grid md:grid-cols-2 gap-4">
              <div className="p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <div className="w-3 h-3 bg-blue-600 rounded-full"></div>
                  形状规则
                </h4>
                <p className="text-sm text-blue-700">圆形、三角形、六边形为正确</p>
              </div>
              
              <div className="p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <div className="w-3 h-3 bg-purple-600 rounded-full"></div>
                  颜色规则
                </h4>
                <p className="text-sm text-purple-700">红色、蓝色、紫色为正确</p>
              </div>
              
              <div className="p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-xl border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  <div className="w-3 h-3 bg-green-600 rounded-full"></div>
                  大小规则
                </h4>
                <p className="text-sm text-green-700">中等、大型尺寸为正确</p>
              </div>
              
              <div className="p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <h4 className="font-semibold text-orange-800 mb-2 flex items-center gap-2">
                  <div className="w-3 h-3 bg-orange-600 rounded-full"></div>
                  组合规则
                </h4>
                <p className="text-sm text-orange-700">大型红色或小型蓝色为正确</p>
              </div>
            </div>

            <div className="bg-gradient-to-r from-amber-50 to-yellow-50 rounded-xl p-6 border border-amber-100">
              <h3 className="font-semibold text-amber-900 mb-4 flex items-center gap-2">
                <Brain className="w-5 h-5" />
                策略提示
              </h3>
              <div className="space-y-2 text-slate-700">
                <p>• <span className="font-semibold">注意规则切换</span>：当前规则会在屏幕上显示</p>
                <p>• <span className="font-semibold">快速适应</span>：规则切换时不要被之前的规则干扰</p>
                <p>• <span className="font-semibold">观察反馈</span>：利用即时反馈调整您的判断策略</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-teal-600 mb-1">80</div>
                <div className="text-sm text-teal-700">试次</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">7</div>
                <div className="text-sm text-cyan-700">分钟限时</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-cyan-50 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">4</div>
                <div className="text-sm text-slate-700">套规则</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const trial = trials[currentTrial];
    const progress = (currentTrial / trials.length) * 100;
    const isSwitch = switchTrials.includes(currentTrial);

    if (!trial) return null;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4 flex-wrap">
            <Badge variant="outline" className="bg-teal-100 text-teal-700 border-teal-300">
              第 {currentTrial + 1} / {trials.length} 次
            </Badge>
            <Badge variant="outline" className={`${
              currentRule === 'shape' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              currentRule === 'color' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              currentRule === 'size' ? 'bg-green-100 text-green-700 border-green-300' :
              'bg-orange-100 text-orange-700 border-orange-300'
            }`}>
              {ruleDefinitions[currentRule].description}
            </Badge>
            {isSwitch && (
              <motion.div
                initial={{ scale: 0.8, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                className="flex items-center"
              >
                <Badge variant="outline" className="bg-red-100 text-red-700 border-red-300 flex items-center gap-1">
                  <Zap className="w-3 h-3" />
                  规则切换！
                </Badge>
              </motion.div>
            )}
            {streakCount >= 5 && (
              <Badge variant="outline" className="bg-emerald-100 text-emerald-700 border-emerald-300 flex items-center gap-1">
                <Target className="w-3 h-3" />
                连续 {streakCount}
              </Badge>
            )}
          </div>
          
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score} / {currentTrial}</span>
            </div>
            <div className="flex items-center gap-2">
              <Clock className="w-4 h-4 text-slate-500" />
              <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
                {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
              </span>
            </div>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 规则提示 */}
        <motion.div
          key={currentRule}
          initial={{ scale: 0.98, opacity: 0.8 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ duration: 0.2 }}
        >
          <Card className={`bg-gradient-to-r ${
            currentRule === 'shape' ? 'from-blue-50 to-blue-100 border-blue-200' :
            currentRule === 'color' ? 'from-purple-50 to-purple-100 border-purple-200' :
            currentRule === 'size' ? 'from-green-50 to-green-100 border-green-200' :
            'from-orange-50 to-orange-100 border-orange-200'
          }`}>
            <CardContent className="py-4">
              <div className="text-center">
                <h3 className={`text-lg font-semibold ${
                  currentRule === 'shape' ? 'text-blue-800' :
                  currentRule === 'color' ? 'text-purple-800' :
                  currentRule === 'size' ? 'text-green-800' :
                  'text-orange-800'
                }`}>
                  当前规则：{ruleDefinitions[currentRule].criteria}
                </h3>
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* 测试区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardContent className="py-12">
            <div className="text-center space-y-8">
              <motion.div
                key={trial.id}
                initial={{ scale: 0.8, opacity: 0, rotateY: 90 }}
                animate={{ scale: 1, opacity: 1, rotateY: 0 }}
                transition={{ duration: 0.4, type: "spring", stiffness: 200 }}
                className="relative"
              >
                {renderShape(trial.shape, trial.color, trial.size)}
                
                {/* 即时反馈 */}
                <AnimatePresence>
                  {feedback.show && (
                    <motion.div
                      initial={{ scale: 0, opacity: 0 }}
                      animate={{ scale: 1, opacity: 1 }}
                      exit={{ scale: 0, opacity: 0 }}
                      className={`absolute -top-4 -right-4 w-12 h-12 rounded-full flex items-center justify-center ${
                        feedback.correct ? 'bg-green-500' : 'bg-red-500'
                      } shadow-lg`}
                    >
                      {feedback.correct ? 
                        <CheckCircle className="w-6 h-6 text-white" /> : 
                        <XCircle className="w-6 h-6 text-white" />
                      }
                    </motion.div>
                  )}
                </AnimatePresence>
                
                {/* 反应时间显示 */}
                <AnimatePresence>
                  {feedback.show && (
                    <motion.div
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -20 }}
                      className="absolute -bottom-8 left-1/2 transform -translate-x-1/2"
                    >
                      <Badge variant="outline" className="bg-white/90 text-slate-600">
                        {feedback.reactionTime}ms
                      </Badge>
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
              
              <h2 className="text-xl font-semibold text-slate-800 mb-6">
                这个图形是否"正确"？
              </h2>
              
              <AnimatePresence>
                {!feedback.show && awaitingResponse && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -20 }}
                    className="flex justify-center gap-6"
                  >
                    <Button
                      onClick={() => handleResponse(true)}
                      className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-12 py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                      size="lg"
                    >
                      正确
                    </Button>
                    <Button
                      onClick={() => handleResponse(false)}
                      className="bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-12 py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                      size="lg"
                    >
                      错误
                    </Button>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    // Ensure we have valid data before processing
    if (!trials.length || !responses.length || !reactionTimes.length) {
      return (
        <div className="max-w-2xl mx-auto text-center p-8">
          <p className="text-slate-600">数据加载中...</p>
        </div>
      );
    }

    // Ensure arrays are synchronized - only process up to the minimum length
    const minLength = Math.min(responses.length, trials.length, reactionTimes.length);
    const validResponses = responses.slice(0, minLength);
    const validTrials = trials.slice(0, minLength);
    const validReactionTimes = reactionTimes.slice(0, minLength);
    
    const correctResponses = validResponses.map((response, index) => 
      response === validTrials[index]?.correct
    ).filter(result => result !== undefined);
    
    const accuracy = correctResponses.length > 0 ? 
      Math.round((correctResponses.filter(Boolean).length / correctResponses.length) * 100) : 0;
    const averageRT = validReactionTimes.length > 0 ? 
      Math.round(validReactionTimes.reduce((sum, rt) => sum + rt, 0) / validReactionTimes.length) : 0;
    
    // 重新计算最终分数
    const switchAccuracy = switchPerformance.total > 0 ? 
      Math.round((switchPerformance.correct / switchPerformance.total) * 100) : 0;
    
    const switchCosts: number[] = [];
    validReactionTimes.forEach((rt, index) => {
      if (switchTrials.includes(index) && index > 0 && !isNaN(rt) && !isNaN(validReactionTimes[index - 1])) {
        switchCosts.push(rt - validReactionTimes[index - 1]);
      }
    });
    
    const averageSwitchCost = switchCosts.length > 0 ? 
      Math.round(switchCosts.reduce((sum, cost) => sum + cost, 0) / switchCosts.length) : 0;
    
    let finalScore = 0;
    finalScore += accuracy * 0.4;
    finalScore += Math.max(0, switchAccuracy - 20) * 0.3;
    finalScore += Math.max(0, Math.min(100, (3000 - averageRT) / 20)) * 0.15;
    
    const rtVariance = validReactionTimes.length > 1 ? 
      validReactionTimes.reduce((sum, rt) => sum + Math.pow(rt - averageRT, 2), 0) / validReactionTimes.length : 0;
    const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 20);
    finalScore += consistencyScore * 0.1;
    finalScore -= Math.min(20, Math.abs(averageSwitchCost) / 50) * 0.05;
    
    finalScore = Math.round(Math.max(0, Math.min(100, finalScore)));

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-teal-600 to-cyan-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">认知灵活性得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-teal-600 mb-1">{accuracy}%</div>
                <div className="text-sm text-teal-700">总体准确率</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">{averageRT}ms</div>
                <div className="text-sm text-cyan-700">平均反应时</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">正确试次</span>
                <span className="font-semibold text-slate-800">{correctResponses.filter(Boolean).length}/{correctResponses.length}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">规则切换次数</span>
                <span className="font-semibold text-slate-800">{switchTrials.length}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">切换试次准确率</span>
                <span className="font-semibold text-slate-800">{switchAccuracy}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">切换成本</span>
                <span className="font-semibold text-slate-800">{averageSwitchCost}ms</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">最长连击</span>
                <span className="font-semibold text-slate-800">{maxStreak}</span>
              </div>
            </div>

            <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-xl p-4 border border-blue-100">
              <h3 className="font-semibold text-blue-900 mb-3 flex items-center gap-2">
                <Brain className="w-5 h-5" />
                表现分析
              </h3>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-600">基础准确率得分</span>
                  <span className="text-blue-600">+{Math.round(accuracy * 0.4)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">切换适应能力</span>
                  <span className="text-green-600">+{Math.round(Math.max(0, switchAccuracy - 20) * 0.3)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">反应速度奖励</span>
                  <span className="text-blue-600">+{Math.round(Math.max(0, Math.min(100, (3000 - averageRT) / 20)) * 0.15)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">一致性得分</span>
                  <span className="text-green-600">+{Math.round((validReactionTimes.length > 1 ? Math.max(0, 100 - Math.sqrt(validReactionTimes.reduce((sum, rt) => sum + Math.pow(rt - averageRT, 2), 0) / validReactionTimes.length) / 20) : 0) * 0.1)}分</span>
                </div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-teal-600 to-cyan-500 hover:from-teal-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}